using System;
using GorillaEngine.Core.Extensions;
using GorillaEngine.ICore;

namespace GorillaEngine.Core.Components {
    public class QuadTree {
        public IQuadTreeObject Root  { get; set; }

        public void Register(IQuadTreeObject quadTreeObject) {

            if (Root == null)
                Root = quadTreeObject;
            else
                RegisterOnProperQuadrant(Root,quadTreeObject);
            

        }

        protected virtual void RegisterOnProperQuadrant(IQuadTreeObject root, IQuadTreeObject child) {
            var quadrant = GetProperQuadrant(root, child);
            if (quadrant != null) {
                RegisterOnProperQuadrant(quadrant, child);
            }
            else {
                SetChild(root, child);
            }
        }

        private static IQuadTreeObject GetProperQuadrant(IQuadTreeObject root, IQuadTreeObject child) {
            IQuadTreeObject quadrant;
            if (root.Position.X < child.Position.X) {
                quadrant = root.Position.Y < child.Position.Y ? root.SW : root.SE;
            }
            else {
                quadrant = root.Position.Y < child.Position.Y ? root.NW : root.NE;
            }
            return quadrant;
        }

        private static void SetChild(IQuadTreeObject root, IQuadTreeObject child) {
            if (root.Position.X < child.Position.X) {
                if (root.Position.Y < child.Position.Y)
                    root.SW = child;
                else {
                    root.SE = child;
                }
            }
            else {
                if (root.Position.Y < child.Position.Y)
                    root.NW = child;
                else
                    root.NE = child;
            }
        }


        public IQuadTreeObject Nearest(IQuadTreeObject quadTreeObject) {

            throw new NotImplementedException();

            IQuadTreeObject nearestObject;

            nearestObject = quadTreeObject;

            var vNE = quadTreeObject.Position.GetVectorTo(quadTreeObject.NE.Position);
            var vNW = quadTreeObject.Position.GetVectorTo(quadTreeObject.NW.Position);
            var vSW = quadTreeObject.Position.GetVectorTo(quadTreeObject.SW.Position);
            var vSE = quadTreeObject.Position.GetVectorTo(quadTreeObject.SE.Position);

            

        }


    }
}